package UDP;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Client {
    public DatagramSocket datagramSocket=null;
    String ip;
    int sort;
    public Client(String ip,int sort) throws UnknownHostException, SocketException {
        datagramSocket=new DatagramSocket();
        this.ip=ip;
        this.sort=sort;
    }
    public void start() throws IOException {
        System.out.println("客户端开始运行");
        Scanner scanner=new Scanner(System.in);
        String response=scanner.nextLine();
        System.out.println("客户端请求数据"+response);
        DatagramPacket datagramPacket1=new DatagramPacket(response.getBytes(),response.getBytes().length, InetAddress.getByName(this.ip),this.sort);
        datagramSocket.send(datagramPacket1);
        DatagramPacket datagramPacket2=new DatagramPacket(new byte[4096],4096);
        datagramSocket.receive(datagramPacket2);
        String request=new String(datagramPacket2.getData(),0,datagramPacket2.getLength());
        System.out.println("服务器响应数据，客户端收到"+request);
    }
    public static void main(String[] args) throws IOException {
        Client client=new Client("127.0.0.1",9090);
        client.start();
    }
}
